// 全局变量
let currentDisplayedData = {};
let refreshInterval = null;
let allItems = []; // 存储所有监控项
let pausedItems = new Set(); // 存储暂停的项目
let notificationTimeout = null; // 通知定时器

// 显示消息通知的函数
function showMessage(message) {
    // 清除之前的定时器
    if (notificationTimeout) {
        clearTimeout(notificationTimeout);
    }
    
    // 获取或创建通知元素
    let notification = document.getElementById('messageNotification');
    if (!notification) {
        notification = document.createElement('div');
        notification.id = 'messageNotification';
        notification.className = 'notification';
        document.body.appendChild(notification);
    }
    
    // 设置通知内容和样式
    notification.textContent = message;
    notification.style.display = 'block';
    
    // 1.5秒后自动隐藏通知
    notificationTimeout = setTimeout(function() {
        notification.style.display = 'none';
    }, 1500);
}

// 显示执行结果的函数
function showExecutionResults(results) {
    let resultMessage = "执行完成:";
    results.forEach(result => {
        resultMessage += `\n${result.desc} (${result.ip}): ${result.result}`;
    });
    showMessage(resultMessage);
}

// 初始化函数
// 初始化函数
// 初始化函数
function initializeApp() {
    // 确保pywebview API已加载
    if (window.pywebview && window.pywebview.api) {
        // 获取初始数据
        Promise.all([
            window.pywebview.api.get_initial_data(),
            window.pywebview.api.get_all_items()
        ]).then(function(responses) {
            const data = responses[0];
            allItems = responses[1];
            
            // 填充表格
            renderTable(data.config, data.stats);
            
            // 设置初始值
            document.getElementById('intervalInput').value = data.interval;
            document.getElementById('threadsInput').value = data.max_workers;
            document.getElementById('statusLabel').textContent = data.status;
            
            // 更新暂停项目列表
            pausedItems = new Set(data.paused_items || []);
            
            // 开始定期更新
            startDataRefresh();
        }).catch(function(error) {
            console.error('获取初始数据失败:', error);
            showMessage('初始化失败: ' + error.message);
        });
    } else {
        // 如果API未加载，稍后重试
        setTimeout(initializeApp, 100);
    }
}

// 渲染表格
function renderTable(config, stats) {
    const tbody = document.getElementById('tableBody');
    tbody.innerHTML = '';
    
    config.forEach((item, index) => {
        const id = index + 1;
        const key = id.toString();
        const stat = stats[key] || { 
            success: 0, 
            failure: 0, 
            last_execution: "未执行",
            latest_result: "待检测",
            success_rate: 0
        };
        
        // 获取项目ID（需要从allItems中查找）
        let itemId = "";
        for (let allItem of allItems) {
            if (allItem.ip === item.IP && 
                allItem.port === (item.port || "") && 
                allItem.desc === (item.desc || "")) {
                itemId = allItem.id;
                break;
            }
        }
        
        // 确定项目状态
        const isPaused = pausedItems.has(itemId);
        const statusText = isPaused ? "暂停" : "运行中";
        const statusClass = isPaused ? "bg-warning" : "bg-success";
        
        const row = document.createElement('tr');
        row.setAttribute('data-key', key);
        
        // 设置行内容
        row.innerHTML = `
            <td><input type="checkbox" class="row-checkbox" data-id="${itemId}"></td>
            <td>${id}</td>
            <td>${item.desc || ''}</td>
            <td>${item.IP}</td>
            <td>${item.port || ''}</td>
            <td><span class="badge ${statusClass}">${statusText}</span></td>
            <td>
                <div class="d-flex align-items-center">
                    <span class="me-2">${stat.success_rate.toFixed(2)}%</span>
                    <div class="progress flex-grow-1" style="height: 8px;">
                        <div class="progress-bar bg-success" role="progressbar" 
                             style="width: ${stat.success_rate}%" aria-valuenow="${stat.success_rate}" 
                             aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                </div>
            </td>
            <td>${stat.success}</td>
            <td>${stat.failure}</td>
            <td>${stat.last_execution}</td>
            <td class="${stat.latest_result === '成功' ? 'text-success' : 'text-danger'}">
                <span class="badge ${stat.latest_result === '成功' ? 'bg-success' : 'bg-danger'}">
                    ${stat.latest_result}
                </span>
            </td>
            <td>${item.port ? 'Socket' : 'Ping'}</td>
        `;
        
        tbody.appendChild(row);
    });
    
    // 更新当前显示的数据引用
    currentDisplayedData = {...stats};
}

// 开始定期刷新数据
function startDataRefresh() {
    // 清除现有定时器
    if (refreshInterval) {
        clearInterval(refreshInterval);
    }
    
    // 设置新的定时器
    refreshInterval = setInterval(function() {
        if (window.pywebview && window.pywebview.api) {
            Promise.all([
                window.pywebview.api.get_initial_data(),
                window.pywebview.api.get_all_items()
            ]).then(function(responses) {
                const response = responses[0];
                allItems = responses[1];
                
                updateTableWithNewData(response.stats);
                // 更新暂停项目列表
                pausedItems = new Set(response.paused_items || []);
            }).catch(function(error) {
                console.error('获取数据失败:', error);
            });
        }
    }, 2000); // 每2秒刷新一次
}

// 使用新数据更新表格，仅当数据确实发生变化时
function updateTableWithNewData(newData) {
    let hasChanged = false;
    
    // 遍历新数据，与当前显示的数据比较
    for (const [key, newStat] of Object.entries(newData)) {
        const oldStat = currentDisplayedData[key];
        
        // 如果该键不存在于旧数据中，或者数据有变化，则需要更新
        if (!oldStat || hasDataChanged(oldStat, newStat)) {
            updateTableRow(key, newStat);
            hasChanged = true;
        }
    }
    
    // 更新当前显示的数据引用
    if (hasChanged) {
        currentDisplayedData = {...newData};
    }
}

// 比较两个数据对象是否不同
function hasDataChanged(oldData, newData) {
    // 只比较需要在界面上展示的字段
    return oldData.success !== newData.success ||
           oldData.failure !== newData.failure ||
           oldData.latest_result !== newData.latest_result ||
           oldData.last_execution !== newData.last_execution ||
           oldData.success_rate !== newData.success_rate;
}

// 更新表格中的单行
function updateTableRow(key, stat) {
    // 根据 key 找到对应的行
    const row = document.querySelector(`tr[data-key="${key}"]`);
    if (!row) return; // 如果行不存在，则返回
    
    // 更新行的各个单元格
    // 更新状态
    // 首先需要获取itemId来确定暂停状态
    const checkbox = row.querySelector('.row-checkbox');
    const itemId = checkbox ? parseInt(checkbox.dataset.id) : null;
    if (itemId) {
        const statusCell = row.querySelector('td:nth-child(6)');
        const isPaused = pausedItems.has(itemId);
        const statusText = isPaused ? "暂停" : "运行中";
        const statusClass = isPaused ? "bg-warning" : "bg-success";
        statusCell.innerHTML = `<span class="badge ${statusClass}">${statusText}</span>`;
    }
    
    // 更新成功率
    const successRateCell = row.querySelector('td:nth-child(7)');
    successRateCell.querySelector('span').textContent = `${stat.success_rate.toFixed(2)}%`;
    successRateCell.querySelector('.progress-bar').style.width = `${stat.success_rate}%`;
    
    // 更新成功次数
    row.querySelector('td:nth-child(8)').textContent = stat.success;
    
    // 更新失败次数
    row.querySelector('td:nth-child(9)').textContent = stat.failure;
    
    // 更新上一次执行时间
    row.querySelector('td:nth-child(10)').textContent = stat.last_execution;
    
    // 更新最新检测结果及其样式
    const resultCell = row.querySelector('td:nth-child(11)');
    const badge = resultCell.querySelector('.badge');
    badge.textContent = stat.latest_result;
    badge.className = `badge ${stat.latest_result === '成功' ? 'bg-success' : 'bg-danger'}`;
}

// 更新设置
function updateSettings() {
    const interval = document.getElementById('intervalInput').value;
    const maxThreads = document.getElementById('threadsInput').value;
    
    if (window.pywebview && window.pywebview.api) {
        window.pywebview.api.update_settings(interval, maxThreads).then(function(response) {
            if (response.status === 'success') {
                document.getElementById('statusLabel').textContent = "参数已更新";
                document.getElementById('statusLabel').className = 'badge bg-info';
                
                // 短暂显示后恢复
                setTimeout(function() {
                    document.getElementById('statusLabel').className = 'badge bg-success';
                    document.getElementById('statusLabel').textContent = "运行中";
                }, 2000);
            } else {
                showMessage('更新失败: ' + response.message);
            }
        }).catch(function(error) {
            showMessage('更新设置失败: ' + error.message);
        });
    }
}

// 主题切换
function setupThemeSwitcher() {
    document.getElementById('lightThemeBtn').addEventListener('click', function() {
        document.body.classList.remove('dark-theme');
        document.body.classList.add('light-theme');
        localStorage.setItem('theme', 'light');
    });
    
    document.getElementById('darkThemeBtn').addEventListener('click', function() {
        document.body.classList.remove('light-theme');
        document.body.classList.add('dark-theme');
        localStorage.setItem('theme', 'dark');
    });
    
    // 加载保存的主题
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme === 'dark') {
        document.body.classList.remove('light-theme');
        document.body.classList.add('dark-theme');
    }
}

// 绑定事件
function bindEvents() {
    document.getElementById('updateBtn').addEventListener('click', updateSettings);
    setupThemeSwitcher();
    
    // 绑定全选复选框
    document.getElementById('selectAll').addEventListener('change', function() {
        const checkboxes = document.querySelectorAll('.row-checkbox');
        checkboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
    });
    
    // 绑定新增按钮
    document.getElementById('addBtn').addEventListener('click', function() {
        const modal = new bootstrap.Modal(document.getElementById('addItemModal'));
        document.getElementById('addItemForm').reset();
        modal.show();
    });
    
    // 绑定保存按钮
    document.getElementById('saveItemBtn').addEventListener('click', function() {
        const desc = document.getElementById('itemDesc').value;
        const ip = document.getElementById('itemIP').value;
        const port = document.getElementById('itemPort').value;
        
        if (!desc || !ip) {
            showMessage('请填写必填字段');
            return;
        }
        
        if (window.pywebview && window.pywebview.api) {
            window.pywebview.api.add_item(ip, port, desc).then(function(response) {
                if (response.status === 'success') {
                    // 关闭模态框
                    const modal = bootstrap.Modal.getInstance(document.getElementById('addItemModal'));
                    modal.hide();
                    // 刷新数据
                    refreshData();
                    showMessage('添加成功');
                } else {
                    showMessage('添加失败: ' + response.message);
                }
            }).catch(function(error) {
                showMessage('添加失败: ' + error.message);
            });
        }
    });
    
    // 绑定删除按钮
    document.getElementById('deleteBtn').addEventListener('click', function() {
        const selectedCheckboxes = document.querySelectorAll('.row-checkbox:checked');
        if (selectedCheckboxes.length === 0) {
            showMessage('请至少选择一项');
            return;
        }
        
        if (!confirm('确定要删除选中的项吗？')) {
            return;
        }
        
        const ids = Array.from(selectedCheckboxes).map(cb => parseInt(cb.dataset.id));
        
        if (window.pywebview && window.pywebview.api) {
            window.pywebview.api.delete_items(ids).then(function(response) {
                if (response.status === 'success') {
                    // 取消全选
                    document.getElementById('selectAll').checked = false;
                    // 刷新数据
                    refreshData();
                    showMessage('删除成功');
                } else {
                    showMessage('删除失败: ' + response.message);
                }
            }).catch(function(error) {
                showMessage('删除失败: ' + error.message);
            });
        }
    });
    
    // 绑定暂停按钮
    document.getElementById('stopBtn').addEventListener('click', function() {
        const selectedCheckboxes = document.querySelectorAll('.row-checkbox:checked');
        if (selectedCheckboxes.length === 0) {
            showMessage('请至少选择一项');
            return;
        }
        
        const ids = Array.from(selectedCheckboxes).map(cb => parseInt(cb.dataset.id));
        
        if (window.pywebview && window.pywebview.api) {
            window.pywebview.api.pause_items(ids).then(function(response) {
                if (response.status === 'success') {
                    // 更新暂停项集合
                    ids.forEach(id => pausedItems.add(id));
                    // 刷新数据
                    refreshData();
                    showMessage('暂停成功');
                } else {
                    showMessage('暂停失败: ' + response.message);
                }
            }).catch(function(error) {
                showMessage('暂停失败: ' + error.message);
            });
        }
    });
    
    // 绑定开启按钮
    document.getElementById('startBtn').addEventListener('click', function() {
        const selectedCheckboxes = document.querySelectorAll('.row-checkbox:checked');
        if (selectedCheckboxes.length === 0) {
            showMessage('请至少选择一项');
            return;
        }
        
        const ids = Array.from(selectedCheckboxes).map(cb => parseInt(cb.dataset.id));
        
        if (window.pywebview && window.pywebview.api) {
            window.pywebview.api.resume_items(ids).then(function(response) {
                if (response.status === 'success') {
                    // 更新暂停项集合
                    ids.forEach(id => pausedItems.delete(id));
                    // 刷新数据
                    refreshData();
                    showMessage('恢复成功');
                } else {
                    showMessage('恢复失败: ' + response.message);
                }
            }).catch(function(error) {
                showMessage('恢复失败: ' + error.message);
            });
        }
    });
    
    // 绑定立即执行按钮
    document.getElementById('executeNowBtn').addEventListener('click', function() {
        const selectedCheckboxes = document.querySelectorAll('.row-checkbox:checked');
        let ids = null;
        
        // 如果有选中的项，则只执行选中的项
        if (selectedCheckboxes.length > 0) {
            ids = Array.from(selectedCheckboxes).map(cb => parseInt(cb.dataset.id));
        }
        // 如果没有选中的项，则会执行所有启用的项
        
        if (window.pywebview && window.pywebview.api) {
            window.pywebview.api.execute_items_now(ids).then(function(response) {
                if (response.status === 'success') {
                    // 显示执行结果
                    showExecutionResults(response.results);
                    // 刷新数据
                    refreshData();
                } else {
                    showMessage('执行失败: ' + response.message);
                }
            }).catch(function(error) {
                showMessage('执行失败: ' + error.message);
            });
        }
    });
}

// 刷新数据
function refreshData() {
    if (window.pywebview && window.pywebview.api) {
        Promise.all([
            window.pywebview.api.get_initial_data(),
            window.pywebview.api.get_all_items()
        ]).then(function(responses) {
            const data = responses[0];
            allItems = responses[1];
            
            renderTable(data.config, data.stats);
            // 更新暂停项目列表
            pausedItems = new Set(data.paused_items || []);
        }).catch(function(error) {
            console.error('刷新数据失败:', error);
            showMessage('刷新数据失败: ' + error.message);
        });
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    bindEvents();
    initializeApp();
});